package xxl.robotlegs.base.lifecycle 
{
	import xxl.signals.base.DeluxeSignal;
	import xxl.signals.base.events.GenericEvent;
	import xxl.signals.base.MapSignal;
	import xxl.signals.core.ISignal;
	import xxl.signals.core.ISlot;
	
	/**
	 * ...
	 * @author XXL
	 */
	public class LifecycleSignal extends MapSignal 
	{
		public static const ERROR:String = "_error";

		public static const STATE_CHANGE:String = "stateChange";

		public static const PRE_INITIALIZE:String = "preInitialize";

		public static const INITIALIZE:String = "initialize";

		public static const POST_INITIALIZE:String = "postInitialize";

		public static const PRE_SUSPEND:String = "preSuspend";

		public static const SUSPEND:String = "suspend";

		public static const POST_SUSPEND:String = "postSuspend";

		public static const PRE_RESUME:String = "preResume";

		public static const RESUME:String = "resume";

		public static const POST_RESUME:String = "postResume";

		public static const PRE_DESTROY:String = "preDestroy";

		public static const DESTROY:String = "destroy";

		public static const POST_DESTROY:String = "postDestroy";
		
		private var _target:Object;
		
		public function LifecycleSignal(target:Object) 
		{
			_target = target;
			super(DeluxeSignal, String, LifecycleError);
		}
		
		public function dispatchFun(type:String, error:LifecycleError = null):void
		{
			dispatch(type, error);
		}
		
		override protected function registerListenerToMap(key:Object, listener:Function, once:Boolean = false):ISlot 
		{
			const signal:DeluxeSignal = getSignalByKey(key) as DeluxeSignal;
			signal.target = _target;
			if (once)
			{
				return signal.addOnce(listener);
			}
			return signal.add(listener);
		}
		
		[Inline]
		final public function safelyCallBack(callback:Function, type:String, error:LifecycleError):void
		{
			const len:int = callback.length;
			const event:GenericEvent = new GenericEvent();
			event.target = _target;
			event.currentTarget = _target;
			if (len == 0)
			{
				callback();
			}
			else if (len == 1)
			{
				callback(event);
			}
			else if (len == 2)
			{
				callback(event, type);
			}
			else if (len == 3)
			{
				callback(event, type, error);
			}
		}
	}

}